/**
 * 
 */
package com.glodon.paas.account.dao.mysql;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.jasig.cas.services.RegisteredService;
import org.jasig.cas.services.ServiceRegistryDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.glodon.paas.account.service.util.PaasRegisteredServiceImpl;

/**
 * @author hankl
 *
 */
public class ResourceDetailsUserDetailsService implements UserDetailsService {

	@Autowired
	private ServiceRegistryDao serviceRegistryDao;
	
	private String emptyPassword = "";
	
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.emptyPassword = passwordEncoder.encode("");
	}
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {				 
		List<RegisteredService> serviceList = serviceRegistryDao.load();
		for(RegisteredService s : serviceList){			
			if(s.getServiceId().equals(username)){
				String serviceSecret = ((PaasRegisteredServiceImpl)s).getServiceSecret();
				if (serviceSecret== null || serviceSecret.trim().length()==0) {
					serviceSecret = emptyPassword;
				}
				Collection<String> values = new ArrayList<String>();
				values.add(((PaasRegisteredServiceImpl)s).getAuthorities());
				return new User(username, serviceSecret,AuthorityUtils.createAuthorityList(values.toArray(new String[values.size()])) );
			}
		}
		 
		return new User(username,"",AuthorityUtils.createAuthorityList(""));
	}

}
